package com.yulian.util;

import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.Log4JLoggerFactory;
import io.vertx.core.Future;
import io.vertx.core.Promise;
import io.vertx.pgclient.PgPool;
import io.vertx.sqlclient.SqlConnection;

/**
 * @author: renzhenghang
 * date: 2023/7/22 11:13
 * @since: JDK 1.8
 *
 * @description: 数据库连接工具类
 */
public class CommonConnectionUtils {

    final static InternalLogger log = Log4JLoggerFactory.getInstance(CommonConnectionUtils.class);

    /**
     * 获取数据库连接
     *
     * @param client 连接池对象
     * @return 数据库连接
     */
    public static Future<SqlConnection> getCon(PgPool client) {
        Promise<SqlConnection> promise = Promise.promise();
        //从数据库连接池获取连接对象
        client.getConnection(ar1 -> {
            if (ar1.succeeded()) {
                SqlConnection conn = ar1.result();
                promise.complete(conn);
            } else {
                log.info("连接数据库错误信息: " + ar1.cause().toString());
                //这里就相当于继续向上抛出异常，用Promise来向上抛异常
                promise.fail(ar1.cause());
            }
        });
        return promise.future();
    }

}
